namespace MvcApplication1.Tests
{
    using System;
    using System.IO;

    using Noesis.Javascript;

    using NUnit.Framework;

    public class JavascriptNetTestHelper : IDisposable
    {
        private JavascriptContext scriptEngine;

        /// <summary>
        /// You need to use this helper with Unit Tests and not 
        /// Basic Unit Tests because you need a Test Context
        /// </summary>
        public JavascriptNetTestHelper()
        {
            this.scriptEngine = new JavascriptContext();
            this.scriptEngine.SetParameter("console", new Console());
            this.scriptEngine.SetParameter("URL", new UrlHelper());
            this.scriptEngine.SetParameter("Thread", new ThreadHelper());
        }

        /// <summary>
        /// Load the contents of a JavaScript file into the 
        /// Script Engine.
        /// </summary>
        /// <param name="path">Path to JavaScript file</param>
        public void LoadFile(string path)
        {
            this.scriptEngine.Run(File.ReadAllText(path));
        }

        /// <summary>
        /// Pass the path of the test that you want to execute.
        /// </summary>
        /// <param name="testMethodName">JavaScript function name</param>
        public object ExecuteTest(string testMethodName)
        {
            try
            {
                return this.scriptEngine.Run(testMethodName + "()");
            }
            catch (JavascriptException ex)
            {
                throw new AssertionException(ex.Message);
            }
        }

        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        public void Dispose()
        {
            this.scriptEngine.Dispose();
        }
    }
}
